package com.fly.locks.distributed.memcache;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import javax.annotation.PostConstruct;

import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnNotWebApplication;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
@ConditionalOnNotWebApplication
public class MemcachedJob
{
    Runnable runnable;
    
    @Autowired
    MemcachedLockClient memcachedLock;
    
    ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
    
    /**
     * 初始化
     */
    @PostConstruct
    public void init()
    {
        // ****** 重要，先释放锁，防止程序被异常终止，锁未释放 *****
        memcachedLock.remove("key");
        runnable = new MemcachedLockThread(memcachedLock);
    }
    
    @Scheduled(cron = "0/10 * * * * ?")
    public void run()
        throws InterruptedException
    {
        for (int i = 0; i < 5; i++)
        {
            TimeUnit.MILLISECONDS.sleep(RandomUtils.nextInt(0, 100));
            cachedThreadPool.execute(runnable);
        }
    }
}
